import { useEffect, useState } from "react";
import trademarkApi from "@/api/product/trademark";
import { Button, Card, Input, message, Table, Form, Modal, Upload } from "antd";
import type { ColumnsType } from "antd/es/table";
import type { TrademarkData } from "@/api/product/model/trademarkType";
import {
  PlusOutlined,
  FormOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined,
} from "@ant-design/icons";
import { useForm } from "antd/lib/form/Form";
import type { UploadChangeParam } from "antd/es/upload";
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";

export default function Trademark() {
  //结构
  const columns: ColumnsType<TrademarkData> = [
    {
      title: "序号 ",
      dataIndex: "id",
      width: 70,
      align: "center",
      render: (x: any, y: any, index: number) => {
        return index + 1;
      },
    },
    {
      title: "品牌名称",
      dataIndex: "tmName",
      align: "center",
    },
    {
      title: "品牌Logo",
      dataIndex: "logoUrl",
      align: "center",
      render: (x: any) => {
        return <img width="120" height={"60"} src={x}></img>;
      },
    },
    {
      title: "操作",
      dataIndex: "tags",
      align: "center",
      render: (x: any, y: any) => {
        // console.log(y)
        return (
          <div>
            <Button
              icon={<FormOutlined />}
              type="primary"
              onClick={editTrademark(y)}
            >
              修改
            </Button>
            <Button
              onClick={showDeleteConfirm(y)}
              className="ml10"
              icon={<DeleteOutlined />}
              danger
              type="primary"
            >
              删除
            </Button>
          </div>
        );
      },
    },
  ];

  //获得 navigate 函数 设置跳转添加
  // let navigate = useNavigate();
  /* 
  1. 声明一个state数据变量, 名称任意 xxx
  2. 声明一个更新state数据的函数, 名称一般: setXxx 
  3. useState参数指定初始值
  4. 后面更新调用时返回内部存储的最新state数据
  */
  let [current, setCurrent] = useState(1); //左是值,右是设置
  let [pageSize, setPageSize] = useState(5);
  let [total, setTotal] = useState(10);
  let [trademarkList, setTrademarkList] = useState<TrademarkData[]>([]);

  // 初始分页数据展示
  const getTrademarkList = async (page = current) => {
    // console.log(trademarkList.length)
    let res = await trademarkApi.getPageListInfo(page, pageSize);
    setTotal(res.total);
    setTrademarkList(res.records);
  };

  // 单条初始化数据展示
  let [initId, setInitId] = useState("");

  // 点击修改/添加
  const editTrademark = (trade: TrademarkData) => {
    return ()=>{
      // click事件需要回调函数
        form.setFieldsValue(trade);
        setImageUrl(trade.logoUrl); //弹框显示图片用
        // 把初始值变更
        setInitId(trade.id as string)
        setVisible(true);
    }
  };
  // 点击添加
  const addTademark = ()=>{
    return ()=>{
      // 清空数据
      form.resetFields()
      setImageUrl("");
      setInitId("")
      setVisible(true);
    }
  }
  // 点击删除
  const { confirm } = Modal;
  const showDeleteConfirm = (trade: TrademarkData) => {
    return () => {
      confirm({
        title: "警告",
        icon: <ExclamationCircleOutlined />,
        content: `您真的要删除${trade.tmName}吗 `,
        okText: "真个滴",
        okType: "danger",
        cancelText: "不要啊",
        async onOk() {
          try {
            await trademarkApi.remove(trade.id as number);
            message.success("删除成功");
            trademarkList.length > 1
              ? getTrademarkList(current)
              : setCurrent(current - 1);
          } catch (error) {
            Modal.destroyAll();
            message.error("删除失败");
            return Promise.reject(error);
          }
        },
        onCancel() {
          message.warning("删除取消");
        },
      });
    };
  };
  // 点击对话框显示
  const [form] = useForm();
  const [visible, setVisible] = useState(false);

  // 获取表单对象
  // 声明函数 表单完成的事件回调
  let finish = async (value: any) => {
    // 获取表单数据
    let values = form.getFieldsValue();
 
    values.logoUrl = imageUrl;
    values.id = initId
    try {
      await trademarkApi.addOrUpdate(values);
      values.id ? message.success("修改成功") : message.success("添加成功");

      // 总条数 / 每页数 = 总页数
      // console.log((total / pageSize) % 2 )//余数是0表示每页显示刚好,直接去,否则加一去最后一页
      if (values.id) {
        //有id是修改,去当前页
        console.log(current)
        getTrademarkList(current);
      } else {
        //添加
        if (!((total / pageSize) % 2)) {
          //表示需要总页数加一
          setCurrent(total / pageSize + 1);
        } else {
          getTrademarkList(Math.ceil(total / pageSize));
        }
      }
    } catch (error) {
      if (values.id) {
        message.error("修改失败");
      } else {
        message.error("添加失败");
      }
    }
    setVisible(false)
  };
  // 表单取消
  let noAddFrom = () => {
    setVisible(false);
  };


  useEffect(() => {
    // 生命周期钩子,当下面两个值修改重新发一次请求
    getTrademarkList();
  }, [current, pageSize]);

  //   图片上传
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("你只能上传 JPG/PNG 文件");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isLt2M) {
      message.error("文件大小不能超过 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      setLoading(false);
      setImageUrl(info.file.response.data);
      console.log(info)
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}></div>
    </div>
  );

  const baseUrl = process.env.REACT_APP_API;
  const imUrl = baseUrl + "/admin/product/upload";

  return (
    <div>
      <Card bordered style={{ width: "99%", margin: "0 auto" }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={addTademark()}
        >
          添加
        </Button>
      </Card>

      <Card style={{ width: "99%", margin: "10px auto" }}>
        <Table
          rowKey="id"
          bordered
          dataSource={trademarkList}
          columns={columns}
          pagination={{
            total: total, //总条数
            pageSize: pageSize, //每页显示的数量
            current: current, //当前页码
            showQuickJumper: true, //是否显示快速跳转组件
            pageSizeOptions: [4, 6, 9], //调整每页显示的数量 数组
            showSizeChanger: true,
            showTotal: (total) => { 
              return <span>总计 {total} 条</span>;
            },
            onChange(page: number, pageSize: number) {
              setCurrent(page);
              setPageSize(pageSize);
            },
          }}
        ></Table>

        <Modal
          title={initId ? "修改品牌" : "添加品牌"}
          visible={visible}
          footer={null}
          destroyOnClose
          onCancel={noAddFrom}
          forceRender
        >
          <Form
            name="basic"
            onFinish={finish}
            form={form}
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
          >
            <Form.Item
              label="品牌名称"
              name="tmName"
              rules={[{ required: true, message: '请输入品牌名称' }]}
              
            >
              <Input />
            </Form.Item>

            <Form.Item label="品牌图片" valuePropName="logoUrl" name="logoUrl" rules={[{ required: true, message: '请传入图片' }]}>
              <Upload
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action={imUrl}
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {imageUrl ? (
                  <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>

            <Form.Item wrapperCol={{ span: 24, offset: 16 }}>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
              <Button type="dashed" onClick={noAddFrom}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
}
